<template>
  <a-form
    :model="formParams"
    :rules="rules"
    ref="formRef"
    label-placement="left"
    :auto-label-width="true"
    require-mark-placement="left"
  >
    <div class="mb-4">
      <a-divider title-placement="left">基本设置</a-divider>
    </div>

    <a-form-item label="类型" field="menuType">
      <a-radio-group v-model="formParams.menuType" name="menuTypeGroup" type="button">
        <a-radio :key="0" :value="0">目录</a-radio>
        <a-radio :key="1" :value="1">菜单</a-radio>
        <a-radio :key="2" :value="2">按钮</a-radio>
      </a-radio-group>
    </a-form-item>

    <a-form-item :label="`上级${getTypeLable}`" field="parentId">
      <a-tree-select
        :fieldNames="{
          key: 'key',
          title: 'label',
        }"
        placeholder="请选择上级菜单，顶级可不选"
        :data="getPermissionList"
        :fallback-option="false"
        allow-clear
        v-model="formParams.parentId"
      />
    </a-form-item>

    <a-row x-gap="12" :cols="2">
      <a-col>
        <a-form-item :label="`${getTypeLable}名称`" field="menuName">
          <a-input :placeholder="`${getTypeLable}名称`" v-model="formParams.menuName" />
        </a-form-item>
      </a-col>
      <a-col>
        <a-form-item :label="`${getTypeLable}图标`" field="icon">
          <template #label>
            <span>
              <a-tooltip
                :content="`${getTypeLable}图标，填写图标组件名称，需在 src\router\router-icons.ts`"
              >
                <a-icon :size="18" class="mr-1 -mt-1 text-gray-400 cursor-pointer">
                  <QuestionCircleOutlined />
                </a-icon>
              </a-tooltip>
              <span>{{ getTypeLable }}图标</span>
            </span>
          </template>
          <a-input :placeholder="`${getTypeLable}图标映射名称`" v-model="formParams.icon" />
        </a-form-item>
      </a-col>
    </a-row>

    <a-row x-gap="12" :cols="2">
      <a-col>
        <a-form-item field="routeUrl" v-if="formParams.menuType != 2">
          <template #label>
            <span>
              <a-tooltip :content="`路由地址，如：user`">
                <a-icon :size="18" class="mr-1 -mt-1 text-gray-400 cursor-pointer">
                  <QuestionCircleOutlined />
                </a-icon>
              </a-tooltip>
              <span>路由地址</span>
            </span>
          </template>
          <a-input placeholder="路由地址" v-model="formParams.routeUrl" />
        </a-form-item>
      </a-col>
      <a-col>
        <a-form-item field="routeName" v-if="formParams.menuType != 2">
          <template #label>
            <span>
              <a-tooltip
                :content="`对应路由配置文件中 name 只能是唯一性，配置 http(s):// 开头地址 则会新窗口打开`"
              >
                <a-icon :size="18" class="mr-1 -mt-1 text-gray-400 cursor-pointer">
                  <QuestionCircleOutlined />
                </a-icon>
              </a-tooltip>
              <span>路由名称</span>
            </span>
          </template>
          <a-input placeholder="路由名称" v-model="formParams.routeName" />
        </a-form-item>
      </a-col>
    </a-row>

    <a-row x-gap="12" :cols="2" v-if="formParams.menuType > 0">
      <a-col>
        <a-form-item field="permissionCode">
          <template #label>
            <span>
              <a-tooltip :content="`权限标识，也是权限字符，比如 system:menu:list`">
                <a-icon :size="18" class="mr-1 -mt-1 text-gray-400 cursor-pointer">
                  <QuestionCircleOutlined />
                </a-icon>
              </a-tooltip>
              <span>权限标识</span>
            </span>
          </template>
          <a-input placeholder="权限标识 system:user:add" v-model="formParams.permissionCode" />
        </a-form-item>
      </a-col>
      <a-col>
        <a-form-item field="permissionName">
          <template #label>
            <span>
              <a-tooltip :content="`权限名称 对应 权限标识 中文名称`">
                <a-icon :size="18" class="mr-1 -mt-1 text-gray-400 cursor-pointer">
                  <QuestionCircleOutlined />
                </a-icon>
              </a-tooltip>
              <span>权限名称</span>
            </span>
          </template>
          <a-input placeholder="权限名称" v-model="formParams.permissionName" />
        </a-form-item>
      </a-col>
    </a-row>

    <a-row x-gap="12" :cols="2">
      <a-col v-if="formParams.menuType != 2">
        <a-form-item field="redirect">
          <template #label>
            <a-tooltip :content="`默认跳转路由地址，如：/system/menu/menu 多级路由情况下适用`">
              <a-icon :size="18" class="mr-1 -mt-1 text-gray-400 cursor-pointer">
                <QuestionCircleOutlined />
              </a-icon>
            </a-tooltip>
            <span>默认路由</span>
          </template>
          <a-input placeholder="默认跳转路由地址" v-model="formParams.redirect" />
        </a-form-item>
      </a-col>
      <a-col>
        <a-form-item label="显示排序" field="orderNum">
          <a-input-number placeholder="显示排序" v-model="formParams.orderNum" class="w-full" />
        </a-form-item>
      </a-col>
    </a-row>

    <a-row x-gap="12" :cols="1" v-if="formParams.menuType != 2">
      <a-col>
        <a-form-item field="component">
          <template #label>
            <a-tooltip>
              <template #content>
                访问的组件路径，如：`/system/menu/menu`，默认在`views`目录下，默认 `LAYOUT`
                如果是多级菜单 `ParentLayout`
              </template>
              <a-icon :size="18" class="mr-1 -mt-1 text-gray-400 cursor-pointer">
                <QuestionCircleOutlined />
              </a-icon>
            </a-tooltip>
            <span>组件路径</span>
          </template>
          <a-input placeholder="组件路径" v-model="formParams.component" />
        </a-form-item>
      </a-col>
    </a-row>

    <div class="mb-4">
      <a-divider title-placement="left">功能设置</a-divider>
    </div>

    <a-row x-gap="12" :cols="2">
      <a-col>
        <a-form-item field="status">
          <template #label>
            <a-tooltip>
              <template #content> 选择停用则路由将不会出现在侧边栏，也不能被访问 </template>
              <a-icon :size="18" class="mr-1 -mt-1 text-gray-400 cursor-pointer">
                <QuestionCircleOutlined />
              </a-icon>
            </a-tooltip>
            <span>{{ getTypeLable }}状态</span>
          </template>
          <a-radio-group v-model="formParams.status" name="statusGroup" type="button">
            <a-radio :key="0" :value="0">正常</a-radio>
            <a-radio :key="1" :value="1">停用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-col>
      <a-col v-if="formParams.menuType != 2">
        <a-form-item label="根路由" field="isRoot">
          <template #label>
            <a-tooltip>
              <template #content>
                如果使用 `顶部混合菜单`，必须传 true，否则左侧会显示异常
              </template>
              <a-icon :size="18" class="mr-1 -mt-1 text-gray-400 cursor-pointer">
                <QuestionCircleOutlined />
              </a-icon>
            </a-tooltip>
            <span>根路由</span>
          </template>
          <a-switch v-model="formParams.isRoot" />
        </a-form-item>
      </a-col>
    </a-row>

    <a-row x-gap="12" :cols="2" v-if="formParams.menuType != 2">
      <a-col>
        <a-form-item field="isVisible">
          <template #label>
            <a-tooltip>
              <template #content> 选择隐藏则路由将不会出现在侧边栏，但仍然可以访问 </template>
              <a-icon :size="18" class="mr-1 -mt-1 text-gray-400 cursor-pointer">
                <QuestionCircleOutlined />
              </a-icon>
            </a-tooltip>

            <span>显示状态</span>
          </template>
          <a-radio-group v-model="formParams.isVisible" name="isVisibleGroup" type="button">
            <a-radio :key="0" :value="0">显示</a-radio>
            <a-radio :key="1" :value="1">隐藏</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-col>
      <a-col>
        <a-form-item field="isCache">
          <template #label>
            <a-tooltip>
              <template #content>
                选择是则会被`keep-alive`缓存，需要匹配组件的`name`和地址保持一致
              </template>
              <a-icon :size="18" class="mr-1 -mt-1 text-gray-400 cursor-pointer">
                <QuestionCircleOutlined />
              </a-icon>
            </a-tooltip>

            <span>是否缓存</span>
          </template>
          <a-radio-group v-model="formParams.isCache" name="isCacheGroup" type="button">
            <a-radio :key="0" :value="0">缓存</a-radio>
            <a-radio :key="1" :value="1">不缓存</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-col>
    </a-row>

    <a-row x-gap="12" :cols="2" v-if="formParams.menuType != 2">
      <a-col>
        <a-form-item label="是否外链" field="isFrame">
          <template #label>
            <a-tooltip>
              <template #content> 选择是外部地址需以`http(s)://`开头 </template>
              <a-icon :size="18" class="mr-1 -mt-1 text-gray-400 cursor-pointer">
                <QuestionCircleOutlined />
              </a-icon>
            </a-tooltip>
            <span>是否外链</span>
          </template>
          <a-radio-group v-model="formParams.isFrame" name="isFrameGroup" type="button">
            <a-radio :key="0" :value="0">是</a-radio>
            <a-radio :key="1" :value="1">否</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-col>
      <a-col>
        <a-form-item label="简化路由" field="alwaysShow">
          <template #label>
            <a-tooltip>
              <template #content>
                取消自动计算根路由模式 开启之后，当菜单子菜单只有1个的时候，会直接显示子菜单
              </template>
              <a-icon :size="18" class="mr-1 -mt-1 text-gray-400 cursor-pointer">
                <QuestionCircleOutlined />
              </a-icon>
            </a-tooltip>

            <span>简化路由</span>
          </template>
          <a-switch v-model="formParams.alwaysShow" />
        </a-form-item>
      </a-col>
    </a-row>
    <a-row x-gap="12" :cols="1" v-if="formParams.menuType != 2">
      <a-col>
        <a-form-item
          label="外部地址"
          field="frameSrc"
          v-if="formParams.menuType != 2 && formParams.isFrame === 0"
        >
          <a-input placeholder="内联外部地址" v-model="formParams.frameSrc" />
        </a-form-item>
      </a-col>
    </a-row>

    <a-form-item class="submit-form-item" v-if="isShowSubmit">
      <a-button type="primary" :loading="subLoading" @click="formSubmit">保存修改</a-button>
    </a-form-item>
  </a-form>
</template>

<script lang="ts" setup>
  import { ref, computed } from 'vue';
  import { Message, TreeNodeData } from '@arco-design/web-vue';
  import { addMenu, editMenu } from '@/api/system/menu';
  import { QuestionCircleOutlined } from '@vicons/antd';

  const emit = defineEmits(['change']);

  const props = defineProps({
    permissionList: {
      type: Array as PropType<TreeNodeData[]>,
    },
    isShowSubmit: {
      type: Boolean,
      defalut: false,
    },
  });

  const formRef: any = ref(null);
  const subLoading = ref(false);

  const defaultValueRef = () => ({
    id: null,
    parentId: 0,
    activeMenu: '',
    affix: false,
    alwaysShow: false,
    icon: '',
    isRoot: 1,
    isCache: 1,
    isFrame: 1,
    isVisible: 0,
    menuName: '',
    menuType: 0,
    openType: 1,
    status: 0,
    orderNum: null,
    permissionCode: '',
    permissionName: '',
    query: '',
    routeUrl: '',
    routeName: '',
    redirect: '',
    component: '', //目录默认 LAYOUT 多级菜单目录 设置 ParentLayout
  });

  const formParams: any = ref(defaultValueRef());

  const getPermissionList = computed(() => {
    return props.permissionList;
  });

  const getTypeLable = computed(() => {
    const typsStr = ['目录', '菜单', '按钮'];
    return typsStr[formParams.value.menuType];
  });

  const rules = {
    menuName: {
      required: true,
      message: `${getTypeLable.value}名称`,
      trigger: 'blur',
    },
    routeUrl: {
      required: true,
      message: '路由地址不能为空',
      trigger: 'blur',
    },
    component: {
      required: true,
      message: '组件路径不能为空',
      trigger: 'blur',
    },
    routeName: {
      required: true,
      message: '路由名称不能为空',
      trigger: 'blur',
    },
    frameSrc: {
      required: true,
      message: '外部地址不能为空',
      trigger: 'blur',
    },
  };

  function setData(data) {
    formParams.value = data;
    formRef.value?.resetFields();
  }

  function formSubmit(done) {
    formRef.value.validate((errors) => {
      if (errors) {
        Message.error('请填写完整信息');
        subLoading.value = false;
        return done(false);
      }

      if (!formParams.value.id) {
        addMenu(formParams.value)
          .then(() => {
            subLoading.value = false;
            Message.success('添加成功');
            handleReset();
            emit('change');
            return done(true);
          })
          .catch(() => {
            subLoading.value = false;
          });
      } else {
        editMenu(formParams.value)
          .then(() => {
            subLoading.value = false;
            Message.success('修改成功');
            handleReset();
            emit('change');
            return done(true);
          })
          .catch(() => {
            subLoading.value = false;
          });
      }
    });
  }

  function handleReset() {
    formRef.value.resetFields();
    formParams.value = Object.assign(formParams.value, defaultValueRef());
  }

  defineExpose({
    formSubmit,
    handleReset,
    setData,
  });
</script>

<style lang="less" sctep>
  .submit-form-item {
    margin-left: 100px;
  }
</style>
